/*
 * Created on 23-jul-2005
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package org.mushroomdb.engine.statistics;

import java.util.Iterator;

import org.mushroomdb.catalog.Column;
import org.mushroomdb.catalog.Register;
import org.mushroomdb.catalog.Table;
import org.mushroomdb.interceptor.AbstractInterceptor;


/**
 * @author Admin
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class StatisticsLoggerInteceptor extends AbstractInterceptor {

	//Para recordar el estado anterior a un update.
	private int columnIndexToUpdate = 0;
	private Object lastValue = null;
	private Table tableToUpdate = null;


	/**
	 * @see org.mushroomdb.interceptor.Interceptor#afterInsert(com.mdlm.rdbms.catalog.Register, com.mdlm.rdbms.catalog.Table)
	 */
	public void afterInsert(Register register, Table table) {
		StatisticsLogger statisticsLogger = StatisticsLogger.getInstance();
		//Iterator columns = table.getColumns();
		//int i = 1;
		//while (columns.hasNext()) {
			//Column column = (Column)(columns.next());
			statisticsLogger.logAnInsertion(register, table);//statisticsLogger.logAnInsertion(register.getValue(i), column, table);
			//i++;
		//}		
	}
	
	public void beforeUpdate(Register register, int columnIndex, Object object, Table table) {
		this.columnIndexToUpdate = columnIndex;
		this.lastValue = object;
		this.tableToUpdate = table;
	}
	
	public void afterUpdate(Register register, int columnIndex, Object object, Table table) {
		if ((this.columnIndexToUpdate == columnIndex)
			&&(this.tableToUpdate == table)) {
			
			StatisticsLogger statisticsLogger = StatisticsLogger.getInstance();
			Iterator columns = register.getColumns();
			String columnName = null;
			int i = 0;
			while ((columns.hasNext())&&(i < columnIndex)) {
				columnName = ((Column) columns.next()).getName();
				i++;
			}
			Column column = table.getColumn(columnName);
			
			statisticsLogger.logAReplacement(this.lastValue, object, column, table);
			
			this.columnIndexToUpdate = 0;
			this.lastValue = null;
			this.tableToUpdate = null;
		}
	}

}
